package cn.truistic.enmicromsg.main.model;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.util.Log;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

import cn.truistic.enmicromsg.common.util.DeviceUtil;
import cn.truistic.enmicromsg.main.MainMVP;

/**
 * Created by admin on 2018/6/1.
 */

public class ExporModel implements MainMVP.IExportModel {

    private Context context;
    private OnUploadListener onUploadListener;

    public ExporModel( Context context, OnUploadListener onUploadListener ) {
        this.context = context;
        this.onUploadListener = onUploadListener;
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void saveInfoToSharePreferences(String userName, String contactNumber, String password) {
        SharedPreferences sharedPreferences = context.getSharedPreferences("CRMINFO", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", userName);
        editor.putString("contactNumber", contactNumber);
        editor.putString("password", password);
        editor.apply();
    }

    @Override
    public String getPhoneDeviceSerial() {
        return Build.SERIAL;
    }

    @SuppressLint("MissingPermission")
    @Override
    public String getIPAddress() {
        @SuppressLint("WifiManagerLeak") WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }


    public String getUserNameFromSharePreferences () {
        SharedPreferences sharedPreferences = context.getSharedPreferences("CRMINFO", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("username", "");
    }

    public String getPasswordFromSharePreferences() {
        SharedPreferences sharedPreferences = context.getSharedPreferences("CRMINFO", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("password", "");
    }

    public String getContactNumberFromSharePreferences() {
        SharedPreferences sharedPreferences = context.getSharedPreferences("CRMINFO", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("contactNumber", "");
    }

    @Override
    public int getContactsCount() {
        ContentResolver contentResolver = context.getContentResolver();
        int contentCount = 0;
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if ( cursor == null ) {
            return 0;
        }
        while ( cursor.moveToNext() ) {
            contentCount++;
        }
        cursor.close();
        return contentCount;
    }

    @Override
    public void deleteAllContacts() {
        Log.i("INFO", "Start delete all contacts");
        ContentResolver contentResolver = context.getContentResolver();
        ArrayList<String> contactIdList = new ArrayList<>();
        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            return;
        }
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            contactIdList.add(contactId);
        }
        cursor.close();

        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        for (int i = 0; i < contactIdList.size(); i++) {
            ops.add(ContentProviderOperation.newDelete(ContactsContract.Contacts.CONTENT_URI)
                    .withSelection(ContactsContract.Contacts._ID + "=?", new String[]{String.valueOf(contactIdList.get(i))})
                    .withYieldAllowed(true)
                    .build());
            ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(contactIdList.get(i))})
                    .withYieldAllowed(true)
                    .build());
            ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                    .withSelection(ContactsContract.RawContacts.CONTACT_ID + "=?", new String[]{String.valueOf(contactIdList.get(i))})
                    .withYieldAllowed(true)
                    .build());
        }

        try {
            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException | OperationApplicationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteFewContacts() {
        Log.i("INFO", "Start delete all contacts");
        ContentResolver contentResolver = context.getContentResolver();
        ArrayList<String> contactIdList = new ArrayList<>();

        Uri uri = Uri.parse("content://com.android.contacts/contacts");
        Cursor cursor = contentResolver.query(uri, null, null, null, null);
        if (cursor == null) {
            return;
        }
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            contactIdList.add(contactId);
        }
        for (int i = 0; i < contactIdList.size(); i++) {
            Uri deleteIdUri = ContentUris.withAppendedId(uri, Long.parseLong(contactIdList.get(i)));
            contentResolver.delete(deleteIdUri, null, null);
        }
        cursor.close();
    }

    @Override
    public void addManyContact(Map<String, String> contacts) throws RemoteException, OperationApplicationException {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        int rawContactInsertIndex;
        for (Map.Entry<String, String> entry : contacts.entrySet()) {
            rawContactInsertIndex = ops.size();
            String username = entry.getKey();
            String phoneNumber = entry.getValue();
            ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                    .withYieldAllowed(true)
                    .build());
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, username)
                    .withYieldAllowed(true)
                    .build());
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                    .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                    .withYieldAllowed(true)
                    .build());
        }
        context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    }

    @Override
    public void upload(String url, String userName, String password, String phoneNumber, String localIPAddress, String recNum ,String zylx) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        String COORDINATES = "021525374658617185";
        String ENCRYPTIONCHAR = "F5AC95F60BBEDAA9372AE29B84F5E67A";
        String requestUrl = "http://" + url + "/dataForrytz.asmx/WebSelKhsjzy" +
                "?Coordinates=" + COORDINATES +
                "&Encryptionchar=" + ENCRYPTIONCHAR +
                "&optName=" + userName +
                "&recNum=" + recNum +
                "&password=" + password +
                "&opt_MobilePhone=" + phoneNumber +
                "&opt_IP=" + localIPAddress +
                 "&mnqzbh=" + DeviceUtil.getDeviceId(context) +  //设备的id ，没root权限，6.0以上需要加权限
                 "&zylx="+zylx;
        Log.e("TAG", "Request Url: " + requestUrl);
        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (onUploadListener != null) {
                    onUploadListener.onFailure();
                }
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (onUploadListener != null) {
                    onUploadListener.uploadResponse(response);
                }
            }
        });
    }

    //下载完成的监听
    public interface OnUploadListener {

        void onFailure();

        void uploadResponse(Response response);
    }

}
